package com.xiaolong.log.send;

import com.alibaba.fastjson2.JSON;
import com.xiaolong.log.config.LogProperties;
import com.xiaolong.log.msg.ErrorLogMessage;
import com.xiaolong.log.msg.LogMessage;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component

public class RocketMqSendHandler  implements SendHandler{

    private final RocketMQTemplate rocketMQTemplate;
    private final LogProperties logProperties;

    private Logger log = LoggerFactory.getLogger(this.getClass());




    public RocketMqSendHandler(RocketMQTemplate rocketMQTemplate, LogProperties logProperties) {
        this.rocketMQTemplate = rocketMQTemplate;
        this.logProperties = logProperties;
    }


    @Override
    public void sendErr(ErrorLogMessage msg) {
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(msg))
                .build();
        rocketMQTemplate.asyncSend(logProperties.getMessageTopic()+":"+logProperties.getErrorTag(), message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.debug("rocket mq send log success");
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("rocket mq send log success:{}",throwable.getMessage());
            }
        });
    }

    @Override
    public void sendLog(LogMessage msg) {
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(msg)).build();
        rocketMQTemplate.asyncSend(logProperties.getMessageTopic()+":"+logProperties.getMessageTag(), message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.debug("rocket mq send log success");
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("rocket mq send log err:{}",throwable.getMessage());
            }
        });
    }
}
